﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinessHandler;
using EasyCode.Utility;
using System.Text;
public partial class Page_AddNews : System.Web.UI.Page
{
    private New newsItem;
    private NewsController newsController;
    private CategoryController categoryController;
    private NewsPositionController newsPositionController;
    private NewsDataClassesDataContext datacontext;
    private MovieStyleController movieStyleController;
    private string imgFolder = System.Configuration.ConfigurationManager.AppSettings["NEWS_IMG_FOLDER"];
    private ArrayList disableList = new ArrayList();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Session["ImagePath"] = imgFolder;
            this.GetCategory();
            this.GetNewsPosition();
            this.LoadValueForUpdate();
        }
    }

    #region Init Value
    private void InnitValue()
    {
        newsItem.NewsTitle = HttpUtility.HtmlEncode(this.TextBox_NewsTitle.Text.Trim());
        newsItem.NewsDescription = HttpUtility.HtmlEncode(this.TextBox_Description.Text.Trim());
        newsItem.NewsDetail = HttpUtility.HtmlEncode(this.TextBox_Details.Text.Trim());
        newsItem.CreatedDate = DateTime.Now;
        newsItem.LastModifiedDate = DateTime.Now;
        newsItem.SubPageLastModify = DateTime.Now;
        newsItem.PublishDate = Protector.DateTime(this.TextBox_PublishDate.Text, DateTime.Now);
        newsItem.Status = this.CheckBox_IsAcitve.Checked;
        newsItem.ShowHomePage = this.CheckBox_ShowOnHomePage.Checked;
        newsItem.NewsTotalView = 0;
    }
    private void GetCategory()
    {
        categoryController = CategoryController.Instance;
        Dictionary<int, string> myDic = new Dictionary<int, string>();
        int iCount = 0;
        Dictionary<int, string> objListCat = BuilTreeList(ref myDic, ref iCount, categoryController.GetCategoryforInsertNews());
        this.DropDownList_Category.DataSource = objListCat;
        this.DropDownList_Category.DataTextField = "Value";
        this.DropDownList_Category.DataValueField = "Key";
        this.DropDownList_Category.DataBind();
        this.DropDownList_Category.Items.Insert(0, new ListItem("--Select category--", "0"));
        int len = disableList.Count;
        if (len > 0)
        {
            foreach (ListItem item in DropDownList_Category.Items)
            {
                for (int i = 0; i < len; i++)
                {
                    if (item.Value == this.disableList[i].ToString())
                    {
                        item.Attributes.Add("disabled", "disabled");
                        break;
                    }
                }
            }
        }
    }
    private void GetNewsPosition()
    {
        newsPositionController = NewsPositionController.Instance;
        this.DropDownList_HomePagePosition.DataSource = newsPositionController.GetNewsPositionList();
        this.DropDownList_HomePagePosition.DataTextField = "PositionName";
        this.DropDownList_HomePagePosition.DataValueField = "PositionType";
        this.DropDownList_HomePagePosition.DataBind();
        this.DropDownList_HomePagePosition.Items.Insert(0, new ListItem("--Select home page position--", "-1"));
        this.DropDownList_SubPagePosition.DataSource = newsPositionController.GetNewsPositionList();
        this.DropDownList_SubPagePosition.DataTextField = "PositionName";
        this.DropDownList_SubPagePosition.DataValueField = "PositionType";
        this.DropDownList_SubPagePosition.DataBind();
        this.DropDownList_SubPagePosition.Items.Insert(0, new ListItem("--Select sub page position--", "-1"));
        for (int i = DropDownList_SubPagePosition.Items.Count - 1; i >= 0; i--)
        {
            if (DropDownList_SubPagePosition.Items[i].Text.Contains("Middle")
                || DropDownList_SubPagePosition.Items[i].Text.Contains("Left")
                || DropDownList_SubPagePosition.Items[i].Text.Contains("Latest"))
            {
                this.DropDownList_SubPagePosition.Items.RemoveAt(i);
            }
        }
    }
    #endregion
    protected Dictionary<int, string> BuilTreeList(ref Dictionary<int, string> myDic, ref int iCount, List<Category> myList)
    {
        this.categoryController = CategoryController.Instance;
        List<Category> allChild = categoryController.GetAllChildCat();
        foreach (Category item in myList)
        {
            int addKey = Protector.Int(item.CategoryID);
            string addValue = GetStringName(0) + HttpUtility.HtmlDecode(item.CategoryName);
            myDic.Add(addKey, addValue);
            List<Category> objListChild = (from o in allChild
                                           where o.CategoryParentID == addKey
                                           select o).ToList();
            if (objListChild.Count > 0)
            {
                this.disableList.Add(addKey.ToString());
                iCount++;
                BuilTreeListChild(allChild, addKey, ref myDic, ref iCount);
                iCount--;
            }
        }
        if (myDic != null && myList.Count > 0)
        {
            return myDic;
        }
        else
        {
            return new Dictionary<int, string>();
        }
    }
    protected void BuilTreeListChild(List<Category> myListOriginal, int parentID, ref Dictionary<int, string> myDic, ref int iCount)
    {
        List<Category> myList = (from o in myListOriginal
                                 where o.CategoryParentID == parentID
                                 select o).ToList();
        if (myList != null)
        {
            foreach (Category item in myList)
            {
                int addKey = Protector.Int(item.CategoryID);
                string addValue = GetStringName(iCount) + HttpUtility.HtmlDecode(item.CategoryName);
                myDic.Add(addKey, addValue);
                List<Category> objListChild = (from o in myListOriginal
                                               where o.CategoryParentID == addKey
                                               select o).ToList();
                if (objListChild.Count > 0)
                {
                    this.disableList.Add(addKey.ToString());
                    iCount++;
                    BuilTreeListChild(myListOriginal, addKey, ref myDic, ref iCount);
                    iCount--;
                }
            }
        }
    }
    protected string GetStringName(int levelID)
    {
        string abc = "";
        for (int o = 0; o < levelID; o++)
        {
            abc += "|-- ";
        }
        return abc;
    }

    protected void Button_Save_Click(object sender, EventArgs e)
    {
        if (this.Button_Save.Text.Trim().ToUpper() == "SAVE")
        {
            if (!CheckRoles.CanInsert())
            {
                Response.Redirect(ResolveUrl("~/Page/AccessDeny.aspx"));
            }
            this.newsItem = new New();
        }
        else
        {
            if (!CheckRoles.CanEdit())
            {
                Response.Redirect(ResolveUrl("~/Page/AccessDeny.aspx"));
            }
            if (Session["firstid"] == null)
            {
                Response.Redirect("NewsManagement.aspx");
            }
            datacontext = new NewsDataClassesDataContext();
            this.newsItem = (from o in datacontext.News
                             where o.NewsID == Protector.Int(Session["firstid"])
                             select o).SingleOrDefault();
            if (this.newsItem == null)
            {
                Response.Redirect("NewsManagement.aspx");
            }
        }
        this.InnitValue();
        if (this.DropDownList_Category.SelectedIndex == 0 || this.DropDownList_Category.Items.Count < 1)
        {
            this.Message_Alert.SetError(Resources.News.ConfirmSelectCategory);
            this.GetCategory();
            return;
        }
        if (this.TextBox_External.Text.Trim() != string.Empty)
        {
            //if (this.DropDownList_MovieStyle.SelectedIndex < 1)
            //{
            //    this.Message_Alert.SetError(Resources.News.SelectMovieStyle);
            //    return;
            //}
            newsItem.ExternalLink = HttpUtility.HtmlEncode(this.TextBox_External.Text);
            //newsItem.MovieTypeID = Protector.Int(this.DropDownList_MovieStyle.SelectedValue);
            newsItem.Section = HttpUtility.HtmlEncode(this.TextBox_Section.Text.Trim());
            newsItem.Part = HttpUtility.HtmlEncode(this.TextBox_Part.Text.Trim());
            newsItem.Duration = HttpUtility.HtmlEncode(this.TextBox_Duration.Text.Trim());
            newsItem.PrivateLife = HttpUtility.HtmlEncode(this.TextBox_Private.Text.Trim());
            newsItem.MovieKeyword = HttpUtility.HtmlEncode(this.TextBox_MovieKeyword.Text.Trim());
        }
        if (!CheckMovieEmbed())
        {
            int tmp = this.DropDownList_Category.SelectedIndex;
            this.GetCategory();
            this.DropDownList_Category.SelectedIndex = tmp;
            return;
        }
        newsItem.NewsCategoryID = Protector.Int(this.DropDownList_Category.SelectedValue, true);
        if (this.CheckBox_ShowOnHomePage.Checked)
        {
            if (this.DropDownList_HomePagePosition.SelectedIndex == 0 || this.DropDownList_HomePagePosition.Items.Count < 1)
            {
                this.Message_Alert.SetError(Resources.News.ConfirmSelectDisplayPosition);
                int tmp = this.DropDownList_Category.SelectedIndex;
                this.GetCategory();
                this.DropDownList_Category.SelectedIndex = tmp;
                return;
            }
            if (this.Button_Save.Text.Trim().ToUpper() == Resources.News.Update.ToUpper())
            {
                if (Protector.Bool(Session["homestatus"], false) == false)
                {
                    this.newsItem.LastModifiedDate = DateTime.Now;
                    this.newsItem.NewsHomePagePositionID = Protector.Int(this.DropDownList_HomePagePosition.SelectedValue);
                }
                else
                {
                    if (Protector.Int(Session["homeposition"], 0) != Protector.Int(this.DropDownList_HomePagePosition.SelectedValue, 0))
                    {
                        Session["homeposition"] = this.DropDownList_HomePagePosition.SelectedValue;
                        this.newsItem.NewsHomePagePositionID = Protector.Int(this.DropDownList_HomePagePosition.SelectedValue);
                        this.newsItem.LastModifiedDate = DateTime.Now;
                    }
                }
            }
            else
            {
                this.newsItem.LastModifiedDate = DateTime.Now;
                this.newsItem.NewsHomePagePositionID = Protector.Int(this.DropDownList_HomePagePosition.SelectedValue);
            }
        }
        newsItem.NewsCatParentID = this.GetParentID(Protector.Int(this.DropDownList_Category.SelectedValue));
        if (this.DropDownList_SubPagePosition.SelectedIndex == 0 || this.DropDownList_SubPagePosition.Items.Count < 1)
        {
            this.Message_Alert.SetError(Resources.News.ConfirmSelectSubPosition);
            int tmp = this.DropDownList_Category.SelectedIndex;
            this.GetCategory();
            this.DropDownList_Category.SelectedIndex = tmp;
            return;
        }
        else
        {
            if (this.Button_Save.Text.Trim().ToUpper() == Resources.News.Update.ToUpper())
            {
                if (this.newsItem.SubPagePositionID.HasValue && this.newsItem.SubPagePositionID.Value.ToString() != this.DropDownList_SubPagePosition.SelectedValue.ToString())
                {
                    this.newsItem.SubPageLastModify = DateTime.Now;
                    this.newsItem.SubPagePositionID = Protector.Int(this.DropDownList_SubPagePosition.SelectedValue.ToString());
                }
                else if (!this.newsItem.SubPagePositionID.HasValue)
                {
                    this.newsItem.SubPageLastModify = DateTime.Now;
                    this.newsItem.SubPagePositionID = Protector.Int(this.DropDownList_SubPagePosition.SelectedValue.ToString());
                }
            }
            else
            {
                this.newsItem.SubPageLastModify = DateTime.Now;
                this.newsItem.SubPagePositionID = Protector.Int(this.DropDownList_SubPagePosition.SelectedValue.ToString());
            }
        }
        if (this.TextBox_Details.Text.Trim() == string.Empty)
        {
            this.Message_Alert.SetError(Resources.News.ConfirmInputNewsDetail);
            int tmp = this.DropDownList_Category.SelectedIndex;
            this.GetCategory();
            this.DropDownList_Category.SelectedIndex = tmp;
            return;
        }
        DateTime publishDate;
        if (!DateTime.TryParse(this.TextBox_PublishDate.Text, out publishDate))
        {
            this.Message_Alert.SetError(Resources.News.EnterPublishDate);
            int tmp = this.DropDownList_Category.SelectedIndex;
            this.GetCategory();
            this.DropDownList_Category.SelectedIndex = tmp;
            return;
        }
        string avatarFilePath = string.Empty;
        string sliderFilePath = string.Empty;
        string error = string.Empty;
        if (this.FileUpload_Avartar.HasFile)
        {
            if (Commons.Upload(this.FileUpload_Avartar, imgFolder, new string[] { ".png", ".jpg", ".jpeg" }, ref avatarFilePath, ref error))
            {
            }
            else
            {
                this.Message_Alert.SetError(Resources.News.UploadImageError + " " + error);
                return;
            }
        }
        if (this.FileUpload_Slider.HasFile)
        {
            if (Commons.Upload(this.FileUpload_Slider, imgFolder, new string[] { ".png", ".jpg", ".jpeg" }, ref sliderFilePath, ref error))
            {
            }
            else
            {
                this.Message_Alert.SetError(Resources.News.UploadImageError + " " + error);
                int tmp = this.DropDownList_Category.SelectedIndex;
                this.GetCategory();
                this.DropDownList_Category.SelectedIndex = tmp;
                return;
            }
        }
        this.newsItem.PublishDate = publishDate;
        if (!string.IsNullOrEmpty(avatarFilePath))
        {
            this.newsItem.AvatarImage = avatarFilePath;
        }
        if (!string.IsNullOrEmpty(sliderFilePath))
        {
            this.newsItem.SliderPath = sliderFilePath;
        }
        if (this.Button_Save.Text.Trim().ToUpper() == Resources.News.Save.ToUpper())
        {
            try
            {
                newsController = NewsController.Instance;
                newsController.News.InsertOnSubmit(newsItem);
                newsController.SubmitChanges();
                this.Message_Alert.SetSuccess(string.Format(Resources.News.SaveOk, this.TextBox_NewsTitle.Text));
                this.ResetValue();
            }
            catch (Exception ex)
            {
                this.Message_Alert.SetError(string.Format(Resources.News.SaveFail, this.TextBox_NewsTitle.Text) + " Error: " + ex.Message);
            }
        }
        else
        {
            try
            {
                datacontext.SubmitChanges();
                this.Message_Alert.SetSuccess(Resources.News.NewsUpdated);
            }
            catch
            {
                this.Message_Alert.SetError(Resources.News.UpdateFail);
            }
        }
    }
    private void ResetValue()
    {
        this.DropDownList_HomePagePosition.SelectedIndex = 0;
        this.DropDownList_SubPagePosition.SelectedIndex = 0;
        this.TextBox_Description.Text = string.Empty;
        this.TextBox_NewsTitle.Text = string.Empty;
        this.TextBox_PublishDate.Text = string.Empty;
        this.TextBox_Details.Text = string.Empty;
        this.CheckBox_ShowOnHomePage.Checked = false;
        this.TextBox_External.Text = string.Empty;
        //this.DropDownList_MovieStyle.SelectedIndex = 0;
        this.TextBox_Section.Text = string.Empty;
        this.TextBox_Part.Text = string.Empty;
        this.TextBox_Duration.Text = string.Empty;
        this.TextBox_Private.Text = string.Empty;
        this.TextBox_MovieKeyword.Text = string.Empty;
        this.GetCategory();
    }
    private void LoadValueForUpdate()
    {
        int id = Protector.Int(Request.QueryString["id"], 0);
        if (id > 0)
        {
            newsController = NewsController.Instance;
            New item = newsController.GetNewsById(id);
            if (item == null)
            {
                Response.Redirect("NewsManagement.aspx");
            }
            this.TextBox_NewsTitle.Text = HttpUtility.HtmlDecode(item.NewsTitle);
            this.TextBox_Description.Text = HttpUtility.HtmlDecode(item.NewsDescription);
            this.TextBox_Details.Text = HttpUtility.HtmlDecode(item.NewsDetail);
            if (item.ShowHomePage.HasValue && item.ShowHomePage.Value == true)
            {
                this.CheckBox_ShowOnHomePage.Checked = true;
                this.DropDownList_HomePagePosition.SelectedValue = item.NewsHomePagePositionID.ToString();
            }
            this.DropDownList_SubPagePosition.SelectedValue = item.SubPagePositionID.ToString();
            this.DropDownList_Category.SelectedValue = item.NewsCategoryID.ToString();

            //this.DropDownList_MovieStyle.SelectedValue = item.MovieTypeID.Value.ToString();
            this.TextBox_External.Text = HttpUtility.HtmlDecode(item.ExternalLink);
            this.TextBox_Section.Text = HttpUtility.HtmlDecode(item.Section);
            this.TextBox_Part.Text = HttpUtility.HtmlDecode(item.Part);
            this.TextBox_Duration.Text = HttpUtility.HtmlDecode(item.Duration);
            this.TextBox_Private.Text = HttpUtility.HtmlDecode(item.PrivateLife);
            this.TextBox_MovieKeyword.Text = HttpUtility.HtmlDecode(item.MovieKeyword);

            this.TextBox_PublishDate.Text = item.PublishDate.Value.ToShortDateString();
            this.Button_Save.Text = Resources.News.Update;
            Session["firstid"] = id;
            Session["homeposition"] = item.NewsHomePagePositionID;
            Session["homestatus"] = item.ShowHomePage;
        }
    }
    List<Category> catList = null;
    private int? GetParentID(int childID)
    {
        categoryController = CategoryController.Instance;
        catList = categoryController.GetAllCat();
        if (catList == null)
        {
            return null;
        }
        return GetRoot(childID);

    }
    private int? GetRoot(int? child)
    {
        foreach (Category item in catList)
        {
            if (item.CategoryID == child && item.CategoryParentID == null)
            {
                return item.CategoryID;
            }
            else if (item.CategoryID == child)
            {
                return GetRoot(item.CategoryParentID);
            }
        }
        return null;
    }
    private bool CheckMovieEmbed()
    {
        if (this.DropDownList_SubPagePosition.SelectedItem.Text == "Top Banner")
        {
            if (this.DropDownList_Category.SelectedItem.Text.Contains("Movie")
                || this.DropDownList_Category.SelectedItem.Text.Contains("Music"))
            {
                if (string.IsNullOrEmpty(this.TextBox_External.Text))
                {
                    this.Message_Alert.SetError(Resources.News.ConfirmEnterExternalLink);
                    return false;
                }
            }
            else
            {
                int? rootID = GetParentID(Protector.Int(this.DropDownList_Category.SelectedValue));
                if (rootID.HasValue)
                {
                    categoryController = CategoryController.Instance;
                    Category item = categoryController.GetCatByID(rootID.Value);
                    if (item != null && (item.CategoryName.ToUpper() == "CNTV" || item.CategoryName.ToUpper() == "CNTV LIVE"))
                    {
                        if (string.IsNullOrEmpty(this.TextBox_External.Text))
                        {
                            this.Message_Alert.SetError(Resources.News.ConfirmEnterExternalLink);
                            return false;
                        }
                    }
                }
            }
        }
        return true;
    }
}